#-*- coding:utf8-*-

import networkx as nx
import matplotlib.pyplot as plt
import re

def initGraph():
        targets = {}
        labels = {}
        graphFile = open('graph')
        content = graphFile.readlines()
        verticesNumber = int(content[0].split('\n')[0])
        G = nx.Graph()
        for i in range(1, verticesNumber+1):
                G.add_node(i)
                labels[i] = i
        search = re.search(r'Exit:(.*)', content[1].split('\n')[0])
        target = search.group(1).split(' ')
        G.add_node(0)
        labels[0] = 0
        j = 0
        for i in range(0, len(target)):
                if target[i] != '':
                        targets[j] = target[i]
                        j = j + 1
        for i in range(0, len(targets)):
                G.add_weighted_edges_from([(0, int(targets[i]), 100)])
        for i in range(2, len(content)):
                search = re.search(r'\[(\d+), (\d+), (\d+)\]', content[i].split('\n')[0])
                if search:
                        G.add_weighted_edges_from([(int(search.group(1)), int(search.group(2)), int(search.group(3)))])
        edge_labels = nx.get_edge_attributes(G, 'weight')
        pos=nx.circular_layout(G)
        nx.draw_networkx_nodes(G, pos, node_color='g', node_size=500, alpha=0.8)
        nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, edge_color='b')
        nx.draw_networkx_labels(G, pos, labels, font_size=16)
        nx.draw_networkx_edge_labels(G, pos, edge_labels)
        return G, labels, targets

def getSingleSourceRoutes(Graph, Source, labels):
        tempGraph = Graph.copy()
        # while len(list(nx.connected_components(tempGraph))) == 1:
        p = nx.shortest_path(tempGraph, source=Source, target=0)
        maxFlow = 100
        for i in range(0, len(p) - 1):
                if tempGraph[p[i]][p[i+1]]['weight'] < maxFlow:
                        maxFlow = tempGraph[p[i]][p[i+1]]['weight']
        for i in range(0, len(p) - 1):
                tempGraph[p[i]][p[i + 1]]['weight'] = tempGraph[p[i]][p[i+1]]['weight'] - maxFlow
                if tempGraph[p[i]][p[i+1]]['weight'] == 0:
                        tempGraph.remove_edge(p[i], p[i+1])
        edge_labels = nx.get_edge_attributes(tempGraph, 'weight')
        pos = nx.circular_layout(tempGraph)
        nx.draw_networkx_nodes(tempGraph, pos, node_color='g', node_size=500, alpha=0.8)
        nx.draw_networkx_edges(tempGraph, pos, width=1.0, alpha=0.5, edge_color='b')
        nx.draw_networkx_labels(tempGraph, pos, labels, font_size=16)
        nx.draw_networkx_edge_labels(tempGraph, pos, edge_labels)
        plt.axis('off')
        plt.savefig("reduce.png")
        plt.draw()


if __name__ == "__main__":
        Graph, labels, targets = initGraph()
        getSingleSourceRoutes(Graph, 1, labels)
        plt.axis('off')
        plt.savefig("example.png")
        plt.draw()